package com.harbor.java.domain;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description : 超市实体类
 * @Author : lxj
 * @CreateTime : 2025/7/15 16:36
 */
public class SuperMarket {
    private final Map<Integer, Fruit> fruits; //存储水果信息

    private final double[] discountPromotion = new double[2];

    public SuperMarket() {
        fruits = new HashMap<>();
    }

    /**
     * 新增一种水果
     * @param fruit 水果对象
     */
    public int addFruit(Fruit fruit) {
        int id = fruit.getId();
        fruits.put(id, fruit);

        return id;
    }

    /**
     * 开启满减活动，消费满total元减免discount元
     * @param total 需要达到的额度
     * @param discount 优惠额度
     */
    public void startDiscountPromotion(double total, double discount) {
        discountPromotion[0] = total;
        discountPromotion[1] = discount;
    }

    /**
     * 结算购物车价格
     * @param shoppingCart 购物车
     * @return 购物车总额
     */
    public double settlementPrice(ShoppingCart shoppingCart) {
        double res = 0;

        Map<Integer, Double> cartMap = shoppingCart.getCartMap();
        for (Integer itemId : cartMap.keySet()) {
            Fruit fruit = fruits.get(itemId);
            // 物品数量
            Double num = cartMap.get(itemId);
            // 物品单价和折扣
            double pricePerKg = fruit.getPricePerKg(), discount = fruit.getDiscount();

            // 计算价格
            double sum = pricePerKg * num * discount;
            res += sum;
        }

        // 满减活动
        double total = discountPromotion[0], discount = discountPromotion[1];
        if (total > 0 && res > total) {
            res = Math.max(0, res - discount);
        }

        return res;
    }
}